import React, { createRef, forwardRef, useEffect, useRef } from "react"
class ChildClassComponent extends React.Component {
render() {
let { title } = this.props
return <div>{title}</div>
}
}
const ChildFunctionalComponent = forwardRef((props, ref) => {
return (
<>
<div id="myId1" ref={ref}>
child2
</div>
{}
{
}
</>
)
})
const ChildFunctionalComponentWithoutForwardRef = (props, ref) => {
let { title } = props
return (
<div id="myId3" ref={ref}>
{title}
</div>
)
}
export default function Demo() {
let childWithLocalVariable1 = null
let childWithLocalVariable2 = null
let childClassComponentWithUseRef = useRef()
let childClassComponentWithCreateRef = createRef()
let childFunctionalComponentWithCreateRef = createRef()
let childFunctionalComponentWithUseRef = useRef()
useEffect(() => {
console.log(childWithLocalVariable1)
console.log(childWithLocalVariable2)
console.log(childClassComponentWithUseRef)
console.log(childClassComponentWithCreateRef)
console.log(childFunctionalComponentWithCreateRef)
console.log(childFunctionalComponentWithUseRef)
}, [])
return (
<div>
<ChildClassComponent
ref={childWithLocalVariable1}
title="直接使用局部变量,这种方式拿到的会是null"
/>
<ChildClassComponent
ref={(x) => (childWithLocalVariable2 = x)}
title="直接使用局部变量,这种方式可以拿到dom对象"
/>
<ChildClassComponent
ref={childClassComponentWithUseRef}
title="childClassComponentWithUseRef"
/>
<ChildClassComponent
ref={childClassComponentWithCreateRef}
title="childClassComponentWithCreateRef"
/>
<ChildFunctionalComponent
ref={childFunctionalComponentWithCreateRef}
title="childFunctionalComponentWithCreateRef"
/>
<ChildFunctionalComponent
ref={childFunctionalComponentWithUseRef}
title="childFunctionalComponentWithUseRef"
/>
{}
</div>
)
}